import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../theme/app_theme.dart';

/// Markdown 编辑器组件
/// 支持实时预览和格式化工具栏
class MarkdownEditor extends StatefulWidget {
  final String? initialTitle;
  final String? initialContent;
  final Function(String title)? onTitleChanged;
  final Function(String content)? onContentChanged;
  final VoidCallback? onSave;

  const MarkdownEditor({
    super.key,
    this.initialTitle,
    this.initialContent,
    this.onTitleChanged,
    this.onContentChanged,
    this.onSave,
  });

  @override
  State<MarkdownEditor> createState() => _MarkdownEditorState();
}

class _MarkdownEditorState extends State<MarkdownEditor> {
  late TextEditingController _titleController;
  late TextEditingController _contentController;
  late FocusNode _titleFocusNode;
  late FocusNode _contentFocusNode;
  
  bool _isPreviewMode = false;
  bool _isFullscreen = false;

  @override
  void initState() {
    super.initState();
    _titleController = TextEditingController(text: widget.initialTitle ?? '');
    _contentController = TextEditingController(text: widget.initialContent ?? '');
    _titleFocusNode = FocusNode();
    _contentFocusNode = FocusNode();
    
    _titleController.addListener(() {
      widget.onTitleChanged?.call(_titleController.text);
    });
    
    _contentController.addListener(() {
      widget.onContentChanged?.call(_contentController.text);
    });
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    _titleFocusNode.dispose();
    _contentFocusNode.dispose();
    super.dispose();
  }

  /// 插入 Markdown 格式
  void _insertMarkdown(String prefix, [String suffix = '']) {
    final text = _contentController.text;
    final selection = _contentController.selection;
    
    if (selection.isValid && selection.start != selection.end) {
      // 有选中文本
      final selectedText = text.substring(selection.start, selection.end);
      final newText = text.replaceRange(
        selection.start,
        selection.end,
        '$prefix$selectedText$suffix',
      );
      
      _contentController.text = newText;
      _contentController.selection = TextSelection.collapsed(
        offset: selection.start + prefix.length + selectedText.length + suffix.length,
      );
    } else {
      // 无选中文本，在光标位置插入
      final cursorPos = selection.baseOffset;
      final newText = text.substring(0, cursorPos) + 
                     prefix + suffix + 
                     text.substring(cursorPos);
      
      _contentController.text = newText;
      _contentController.selection = TextSelection.collapsed(
        offset: cursorPos + prefix.length,
      );
    }
    
    _contentFocusNode.requestFocus();
  }

  /// 构建工具栏
  Widget _buildToolbar() {
    return Container(
      height: 56,
      padding: const EdgeInsets.symmetric(horizontal: 16),
      decoration: const BoxDecoration(
        color: AppTheme.surfaceLight,
        border: Border(
          bottom: BorderSide(
            color: AppTheme.borderColor,
            width: 0.5,
          ),
        ),
      ),
      child: Row(
        children: [
          // 格式化按钮组
          _buildToolbarButton(
            icon: Icons.format_bold,
            tooltip: '粗体 (Ctrl+B)',
            onPressed: () => _insertMarkdown('**', '**'),
          ),
          
          _buildToolbarButton(
            icon: Icons.format_italic,
            tooltip: '斜体 (Ctrl+I)',
            onPressed: () => _insertMarkdown('*', '*'),
          ),
          
          _buildToolbarButton(
            icon: Icons.strikethrough_s,
            tooltip: '删除线',
            onPressed: () => _insertMarkdown('~~', '~~'),
          ),
          
          const SizedBox(width: 8),
          Container(
            width: 1,
            height: 20,
            color: AppTheme.borderColor,
          ),
          const SizedBox(width: 8),
          
          // 标题按钮
          _buildToolbarButton(
            icon: Icons.title,
            tooltip: '标题',
            onPressed: () => _showHeadingMenu(),
          ),
          
          _buildToolbarButton(
            icon: Icons.format_list_bulleted,
            tooltip: '无序列表',
            onPressed: () => _insertMarkdown('- '),
          ),
          
          _buildToolbarButton(
            icon: Icons.format_list_numbered,
            tooltip: '有序列表',
            onPressed: () => _insertMarkdown('1. '),
          ),
          
          _buildToolbarButton(
            icon: Icons.format_quote,
            tooltip: '引用',
            onPressed: () => _insertMarkdown('> '),
          ),
          
          const SizedBox(width: 8),
          Container(
            width: 1,
            height: 20,
            color: AppTheme.borderColor,
          ),
          const SizedBox(width: 8),
          
          // 链接和图片
          _buildToolbarButton(
            icon: Icons.link,
            tooltip: '链接',
            onPressed: () => _insertMarkdown('[', '](url)'),
          ),
          
          _buildToolbarButton(
            icon: Icons.image,
            tooltip: '图片',
            onPressed: () => _insertMarkdown('![', '](url)'),
          ),
          
          _buildToolbarButton(
            icon: Icons.code,
            tooltip: '代码',
            onPressed: () => _insertMarkdown('`', '`'),
          ),
          
          const Spacer(),
          
          // 预览切换
          _buildToolbarButton(
            icon: _isPreviewMode ? Icons.edit : Icons.visibility,
            tooltip: _isPreviewMode ? '编辑模式' : '预览模式',
            isActive: _isPreviewMode,
            onPressed: () {
              setState(() {
                _isPreviewMode = !_isPreviewMode;
              });
            },
          ),
          
          const SizedBox(width: 8),
          
          // 全屏切换
          _buildToolbarButton(
            icon: _isFullscreen ? Icons.fullscreen_exit : Icons.fullscreen,
            tooltip: _isFullscreen ? '退出全屏' : '全屏模式',
            onPressed: () {
              setState(() {
                _isFullscreen = !_isFullscreen;
              });
            },
          ),
        ],
      ),
    );
  }

  /// 构建工具栏按钮
  Widget _buildToolbarButton({
    required IconData icon,
    required String tooltip,
    required VoidCallback onPressed,
    bool isActive = false,
  }) {
    return Tooltip(
      message: tooltip,
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: onPressed,
          borderRadius: BorderRadius.circular(6),
          child: Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: isActive ? AppTheme.primaryColor.withOpacity(0.1) : Colors.transparent,
              borderRadius: BorderRadius.circular(6),
            ),
            child: Icon(
              icon,
              size: 18,
              color: isActive ? AppTheme.primaryColor : AppTheme.textSecondary,
            ),
          ),
        ),
      ),
    );
  }

  /// 显示标题菜单
  void _showHeadingMenu() {
    final RenderBox button = context.findRenderObject() as RenderBox;
    final RenderBox overlay = Overlay.of(context).context.findRenderObject() as RenderBox;
    final RelativeRect position = RelativeRect.fromRect(
      Rect.fromPoints(
        button.localToGlobal(Offset.zero, ancestor: overlay),
        button.localToGlobal(button.size.bottomRight(Offset.zero), ancestor: overlay),
      ),
      Offset.zero & overlay.size,
    );

    showMenu<String>(
      context: context,
      position: position,
      items: [
        const PopupMenuItem(value: 'h1', child: Text('# 标题 1')),
        const PopupMenuItem(value: 'h2', child: Text('## 标题 2')),
        const PopupMenuItem(value: 'h3', child: Text('### 标题 3')),
        const PopupMenuItem(value: 'h4', child: Text('#### 标题 4')),
        const PopupMenuItem(value: 'h5', child: Text('##### 标题 5')),
        const PopupMenuItem(value: 'h6', child: Text('###### 标题 6')),
      ],
    ).then((value) {
      if (value != null) {
        final prefix = '${'#' * int.parse(value.substring(1))} ';
        _insertMarkdown(prefix);
      }
    });
  }

  /// 构建编辑区域
  Widget _buildEditArea() {
    return Container(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题输入
          TextField(
            controller: _titleController,
            focusNode: _titleFocusNode,
            style: const TextStyle(
              fontSize: 28,
              fontWeight: FontWeight.w700,
              color: AppTheme.textPrimary,
              height: 1.2,
            ),
            decoration: const InputDecoration(
              hintText: '新笔记',
              hintStyle: TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.w700,
                color: AppTheme.textTertiary,
              ),
              border: InputBorder.none,
              contentPadding: EdgeInsets.zero,
            ),
            maxLines: 1,
          ),
          
          const SizedBox(height: 24),
          
          // 内容输入
          Expanded(
            child: TextField(
              controller: _contentController,
              focusNode: _contentFocusNode,
              style: const TextStyle(
                fontSize: 16,
                color: AppTheme.textPrimary,
                height: 1.6,
              ),
              decoration: const InputDecoration(
                hintText: '开始写作...\n\n支持 Markdown 语法：\n- **粗体** 或 *斜体*\n- # 标题\n- [链接](url)\n- ![图片](url)\n- `代码`\n- > 引用\n- - 列表',
                hintStyle: TextStyle(
                  fontSize: 16,
                  color: AppTheme.textTertiary,
                  height: 1.6,
                ),
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              maxLines: null,
              expands: true,
              textAlignVertical: TextAlignVertical.top,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建预览区域
  Widget _buildPreviewArea() {
    return Container(
      padding: const EdgeInsets.all(24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题预览
          if (_titleController.text.isNotEmpty)
            Text(
              _titleController.text,
              style: const TextStyle(
                fontSize: 28,
                fontWeight: FontWeight.w700,
                color: AppTheme.textPrimary,
                height: 1.2,
              ),
            ),
          
          if (_titleController.text.isNotEmpty)
            const SizedBox(height: 24),
          
          // 内容预览
          Expanded(
            child: _contentController.text.isEmpty
                ? const Center(
                    child: Text(
                      '暂无内容',
                      style: TextStyle(
                        fontSize: 16,
                        color: AppTheme.textTertiary,
                      ),
                    ),
                  )
                : SingleChildScrollView(
                    child: Markdown(
                      data: _contentController.text,
                      selectable: true,
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      styleSheet: MarkdownStyleSheet(
                        p: const TextStyle(
                          fontSize: 16,
                          color: AppTheme.textPrimary,
                          height: 1.6,
                        ),
                        h1: const TextStyle(
                          fontSize: 24,
                          fontWeight: FontWeight.w700,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        h2: const TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        h3: const TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        h4: const TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        h5: const TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        h6: const TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w600,
                          color: AppTheme.textPrimary,
                          height: 1.3,
                        ),
                        code: TextStyle(
                          fontSize: 14,
                          fontFamily: 'monospace',
                          backgroundColor: AppTheme.borderColor.withOpacity(0.1),
                          color: AppTheme.primaryColor,
                        ),
                        codeblockDecoration: BoxDecoration(
                          color: AppTheme.borderColor.withOpacity(0.05),
                          borderRadius: BorderRadius.circular(8),
                          border: Border.all(
                            color: AppTheme.borderColor.withOpacity(0.2),
                          ),
                        ),
                        blockquote: const TextStyle(
                          fontSize: 16,
                          color: AppTheme.textSecondary,
                          fontStyle: FontStyle.italic,
                          height: 1.6,
                        ),
                        blockquoteDecoration: BoxDecoration(
                          border: Border(
                            left: BorderSide(
                              color: AppTheme.primaryColor,
                              width: 4,
                            ),
                          ),
                        ),
                        listBullet: const TextStyle(
                          fontSize: 16,
                          color: AppTheme.textPrimary,
                        ),
                      ),
                    ),
                  ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        children: [
          // 工具栏
          _buildToolbar(),
          
          // 编辑/预览区域
          Expanded(
            child: _isPreviewMode ? _buildPreviewArea() : _buildEditArea(),
          ),
        ],
      ),
    );
  }
}